using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Tauren.Form.Entity.Config;
using Tauren.Form.Entity.Const;
using Tauren.Form.Entity.Global;
using Tauren.Form.Infrastructure.Common;
using Tauren.Form.Infrastructure.RedisHelpe;

namespace Tauren.Form.Infrastructure.Filter
{
    public class SkipAttribute : Attribute, IFilterMetadata
    {
        ///允许未通过身份验证也可以访问的特性
    }

    public class IndetityServrAuthorize : IAuthorizationFilter
    {
        public IRedisClient redisClient;
        public IndetityServrAuthorize(IRedisClient client)
        {
            redisClient = client;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //1.判断是否需要校验
            var isDefined = false;
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor != null)
            {
                isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                   .Any(a => a.GetType().Equals(typeof(SkipAttribute)));
            }

            if (isDefined)
            {
                return;
            }

            var token = context.HttpContext.Request.Headers[GlobalConst.AuthorizationTokenKey].ToString();    //ajax请求传过来
            string grant_type = context.HttpContext.Request.Headers["grant_type"] + "";
            string pattern = "^Bearer (.*?)$";
            if (!Regex.IsMatch(token, pattern))
            {
                context.Result = new ContentResult { StatusCode = 401, Content = "token格式不对!格式为:Bearer {token}" };
                return;
            }
            token = Regex.Match(token, pattern).Groups[1]?.ToString();
            if (token == "null" || string.IsNullOrEmpty(token))
            {
                context.Result = new ContentResult { StatusCode = 401, Content = "token不能为空" };
                return;
            }
            TokenHelper tokenHelper = new TokenHelperExtension().tokenHelper;
            //校验auth的正确性
            var result = JWTHelp.JWTJieM(token, tokenHelper.TokenSecreKey, tokenHelper.IdentityUrl);
            if (result.Any())
            {
                GlobalModel _Global = JsonConvert.DeserializeObject<GlobalModel>(result["sub"] + "");
                string redisKey = $"{grant_type}${_Global.Account.AESEncrypt()}";
                var res = redisClient.GetStringValue(redisKey);
                if (string.IsNullOrEmpty(res))
                {
                    context.Result = new ContentResult { StatusCode = 401, Content = "invalid" };
                    return;
                }
                else { 
                context.HttpContext.Items.Add(GlobalConst.GolbalData, result["sub"]);
                }
            }
            else
            {
                context.Result = new ContentResult { StatusCode = 401, Content = "invalid" };
                return;
            }
        }
    }
}
